package com.shop.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.entity.dto.AdminImages.AdminImagesListDto;
import com.shop.entity.dto.AdminImages.AdminImagesRemoveDto;
import com.shop.entity.pojo.AdminUser;
import com.shop.entity.pojo.Images;
import com.shop.entity.pojo.Style;
import com.shop.entity.pojo.Wares;
import com.shop.admin.mapper.AdminUserMapper;
import com.shop.admin.mapper.ImagesMapper;
import com.shop.admin.mapper.StyleMapper;
import com.shop.admin.mapper.WaresMapper;
import com.shop.admin.service.ImagesService;
import com.shop.file.service.FileStorageService;
import com.shop.utils.common.enums.Code;
import com.shop.utils.common.enums.Message;
import com.shop.utils.common.enums.MessageConstant;
import com.shop.utils.common.result.PageResponseResult;
import com.shop.utils.common.result.Result;
import com.shop.utils.config.BaseContext;
import com.shop.utils.config.LoginFailedException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class ImagesServiceImpl extends ServiceImpl<ImagesMapper, Images> implements ImagesService {

    @Autowired
    private ImagesMapper imagesMapper;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    @Async
    public Result uploadPicture(MultipartFile file, String imagesName) {
        long start = System.currentTimeMillis();
        log.info("后台管理-添加商品素材");
        //1.检查参数
        if(file == null || file.getSize() == Message.Check_Int_Null){
            log.info("参数为空");
            throw new LoginFailedException(MessageConstant.PARAM_REQUIRE);
        }
        List<Images> imagesList = imagesMapper.selectList(Wrappers.<Images>lambdaQuery().eq(Images::getName, imagesName));
        if (!CollectionUtils.isEmpty(imagesList)||imagesList.size()>Message.Check_Int_Null) {
            return Result.errorResult(Code.DATA_EXIST);
        }
        Long adminId = BaseContext.getCurrentId();
        AdminUser adminUser = adminUserMapper.selectById(adminId);
        if (adminUser==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }

        //2.上传图片到minIO中
        String fileName = UUID.randomUUID().toString().replace("-", "");
        //aa.jpg
        String originalFilename = file.getOriginalFilename();
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileId = null;
        try {
            fileId = fileStorageService.uploadImgFile("", fileName + postfix, file.getInputStream());
            log.info("上传图片到MinIO中，fileId:{}",fileId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("WaresImagesServiceImpl-上传文件失败");
        }

        Images waresImages=new Images();
        waresImages=waresImages.builder()
                .url(fileId)
                .name(imagesName)
                .saveAdmin(adminUser.getName())
                .saveTime(String.valueOf(LocalDateTime.now())).build();
        int save = imagesMapper.insert(waresImages);
        if (save==Message.Check_Int_False) {
            log.info("素材添加失败");
            return Result.errorResult(Code.SERVER_ERROR);
        }
        long end = System.currentTimeMillis();
        log.info("后台管理添加商品素材进程完成，总耗时:{}",(end-start));
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result getWaresImagesList(AdminImagesListDto dto) {
        long start = System.currentTimeMillis();
        log.info("后台管理-商品素材列表");
        dto.checkParam();
        Page<Images> page=new Page(dto.getPage(),dto.getSize());
        String key=Message.Admin_key_Images_All;
        Page<Images> check = (Page<Images>) redisTemplate.opsForValue().get(key);
        if (check!=null&&!check.equals("")) {
            log.info("浏览缓存");
            Result result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) check.getTotal());
            result.setData(check.getRecords());
            long end = System.currentTimeMillis();
            log.info("后台管理获取商品素材列表进程完成，总耗时:{}",(end-start));
            return result;
        }
        log.info("浏览数据库");
        Page<Images> value = imagesMapper.getAllByPage(page, dto);
        redisTemplate.opsForValue().set(key,value);
        Result result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) value.getTotal());
        result.setData(value.getRecords());
        long end = System.currentTimeMillis();
        log.info("后台管理获取商品素材列表进程完成，总耗时:{}",(end-start));
        return result;
    }

    @Autowired
    private WaresMapper waresMapper;
    @Autowired
    private StyleMapper styleMapper;
    @Autowired
    private AdminUserMapper adminUserMapper;
    @Override
    public Result removeWaresImages(AdminImagesRemoveDto dto) {
        long start = System.currentTimeMillis();
        log.info("后台管理-删除商品素材");
        if (dto.getRemoveMemo()==null&&dto.getImagesId()==null) {
            log.info("未接收到前端传递的参数");
        }
        Long adminId = BaseContext.getCurrentId();
        AdminUser adminUser = adminUserMapper.selectById(adminId);
        if (adminUser==null||adminId==null) {
            log.info("未查询到该管理员");
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        Images getWaresImages = imagesMapper.selectById(dto.getImagesId());
        if (getWaresImages==null) {
            log.info("未查询到该素材");
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        List<Wares> waresList = waresMapper.selectList(Wrappers.<Wares>lambdaQuery().eq(Wares::getWaresImages, getWaresImages.getUrl()));
        List<Style> styleList = styleMapper.selectList(Wrappers.<Style>lambdaQuery().eq(Style::getStyleImages, getWaresImages.getUrl()));
        if (!CollectionUtils.isEmpty(waresList)||!CollectionUtils.isEmpty(styleList)||waresList.size()> Message.Check_Int_Null||styleList.size()>Message.Check_Int_Null) {
            log.info("有商品正在引用该素材，无法删除");
            log.info("使用该图片的商品:{}",waresList);
            log.info("使用该图片款式的商品:{}",styleList);
            return Result.errorResult(Code.PARAM_INVALID);
        }
        Images waresImages=new Images();
        waresImages=waresImages.builder()
                .removeAdmin(adminUser.getName())
                .removeMemo(dto.getRemoveMemo()).build();
        boolean update = update(waresImages, Wrappers.<Images>lambdaUpdate().eq(Images::getId, dto.getImagesId()));
        if (!update) {
            log.info("修改失败");
            return Result.errorResult(Code.SERVER_ERROR);
        }
        boolean remove = remove(Wrappers.<Images>lambdaUpdate().eq(Images::getId, dto.getImagesId()));
        if (!remove) {
            log.info("删除失败");
            return Result.errorResult(Code.SERVER_ERROR);
        }
        fileStorageService.delete(getWaresImages.getUrl());
        long end = System.currentTimeMillis();
        log.info("后台管理删除商品素材进程完成，总耗时:{}",(end-start));
        return Result.okResult(Code.SUCCESS);
    }

}
